from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
import random
import logging



from celery_tasks.sms.yuntongxun.sms import CCP
# from apps import constants
import constants
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.


logger = logging.getLogger('django')  # 获取日志输入出器


class SMSCodeView(APIView):
    def get(self, request, mobile):
        '''
        /sms_codes/(?P<mobile>1[3-9]\d{9})/
        获取验证码
        :param request: 请求对象
        :param mobile: 手机号
        :return: None
        '''
        # pip3 install django-redis 调用redis
        # 获取redis对象（配置文件为verify_codes）
        redis_conn = get_redis_connection("verify_codes")
        # 获取redis中的值，拼接方式按照验证码+手机号码
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 判断redis中是否存在验证码,在设置的时间内如果有则表示发送频繁
        if send_flag:
            return Response({"message": "发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)
        # 生成验证码
        sms_code = "%06d" % random.randint(0,999999)
        # 写入日志
        logger.info(sms_code)
        # 存储验证码
        # redis_conn.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 验证是否频繁登录
        # redis_conn.setex("send_flag_%s" % mobile, constants.SEND_FLAG_TIME_INTERVAL, 1)

        # 使用管道减少redis访问次数，提高性能
        pl = redis_conn.pipeline()
        pl.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_FLAG_TIME_INTERVAL, 1)
        # 执行管道
        pl.execute()
        # 发送验证码
        # 已经放到异步任务中去实现
        # CCP().send_template_sms(mobile, [sms_code], constants.SMS_TEMP)
        send_sms_code.delay(mobile, sms_code)

        return Response({"message": "OK"})